package com.ma.chapter6.unsafe;

import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.util.ArrayList;
import java.util.List;

@Slf4j(topic = "m.MyAtomicTest")
public class MyAtomicTest {
    public static void main(String[] args) {
        Account.demo(new Account() {
            MyAtomicInteger atomicInteger = new MyAtomicInteger(10000);

            @Override
            public Integer getBalance() {
                return atomicInteger.getValue();
            }

            @Override
            public void withdraw(Integer amount) {
                atomicInteger.decrement(amount);
            }
        });
    }
}

/* Unsafe对象模拟实现原子整数 */
class MyAtomicInteger {
    private volatile int value;
    private static final long valueOffset;
    private static final Unsafe UNSAFE;

    static {
        UNSAFE = UnsafeAccessor.getUnsafe();
        try {
            valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            /* 要通过unsafe对象操作数据就要先获得域的偏移量，可能会有找不到域的异常，异常不会发生，转化为非受查异常 */
            //静态代码块中的异常转换为运行时异常抛出
            throw new RuntimeException(e);
        }
    }

    public int getValue() {
        return value;
    }

    public void decrement(int amount) {
        while (true) {
            int prev = this.value;
            int next = prev - amount;
            if (UNSAFE.compareAndSwapInt(this, valueOffset, prev, next)) {
                break;
            }
        }

    }

    public MyAtomicInteger(int value) {
        this.value = value;
    }

}

interface Account {
    // 获取余额
    Integer getBalance();

    // 取款
    void withdraw(Integer amount);

    /**
     * 方法内会启动 1000 个线程，每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        long start = System.nanoTime();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost: " + (end - start) / 1000_000 + " ms");
    }

}